package org.jsbd.boss.action;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.StringUtils;
import org.jsbd.boss.common.DataGridModel;
import org.jsbd.boss.common.ResponseMapUtils;
import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.domian.SimuatorStatusInfo;
import org.jsbd.boss.domian.channel.SysApkUpgrade;
import org.jsbd.boss.enums.SimulatorTaskStatusEnum;
import org.jsbd.boss.service.ICabinetConfigService;
import org.jsbd.boss.service.ISimuatorStatusInfoService;
import org.jsbd.boss.service.ISysApkUpgradeService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 新版模拟器监控
 * @author lhz
 * @date:   2018年8月27日 下午7:07:19
 */
@Controller
@RequestMapping("/simuatorStatusInfo")
public class SimuatorStatusInfoController {
	public static final Logger LOGGER = LoggerFactory.getLogger(SimuatorStatusInfoController.class);
	
	@Autowired
	private ISimuatorStatusInfoService simuatorStatusInfoService;
	@Autowired
	private RedisClient<String, Object> redisClient;
	@Autowired
	private ICabinetConfigService cabinetConfigService;
	@Autowired
	private ISysApkUpgradeService sysApkUpgradeService;
	
	private static final String ENDPOINT = PropertiesUtil.getValue("oss.endpoint");
	private static final String BUCKETNAME = PropertiesUtil.getValue("oss.bucketName");
	
	/**
	 * 列表页面
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "listModel")
	public String listModel(Model model) throws Exception {
		return "/simuatorStatusInfo/simuatorStatusInfo";
	}
	
	/**
	 * 列表数据
	 * @param page
	 * @param simuatorStatusInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "simuatorStatusInfoPage")
	@ResponseBody
	public Map<String, Object> simuatorStatusInfoPage(DataGridModel page, SimuatorStatusInfo simuatorStatusInfo) throws Exception {
		try{
			simuatorStatusInfo = (simuatorStatusInfo == null ? new SimuatorStatusInfo() : simuatorStatusInfo);
			simuatorStatusInfo.setPageInfo(page);
			
			Map<String, Object> results = new HashMap<String, Object>();
			results.put("total", simuatorStatusInfoService.getListPageCount(simuatorStatusInfo));
			
			List<SimuatorStatusInfo> simuatorStatusInfoList = simuatorStatusInfoService.getSimulatorList(simuatorStatusInfo);
			Map<String, String> cabientMap = cabinetConfigService.getCabinetConfigAllMap();//查询所有机柜
			for (SimuatorStatusInfo config : simuatorStatusInfoList) {
				if (config.getCreateTime() != null) {
					config.setCreateDate(org.jsbd.boss.util.DateUtil.getYmdhmsDateStr(config.getCreateTime()));
				}
				if (config.getModifyTime()!= null) {
					config.setModifyDate(org.jsbd.boss.util.DateUtil.getYmdhmsDateStr(config.getModifyTime()));
				}
				String clientIp = config.getClientIp();
				clientIp = clientIp.replaceAll("/", "");
				clientIp = clientIp.substring(0, clientIp.indexOf(".", clientIp.indexOf(".", clientIp.indexOf(".")+1) +1));
				String cabient = cabientMap.get(clientIp);
				if (StringUtils.isBlank(cabient)) {
					config.setCabinet("未找到机柜");
				} else {
					config.setCabinet(cabient);
				}
			}
			results.put("rows", simuatorStatusInfoList);
			return results;
		}catch(Exception e){
			LOGGER.error("",e);
			throw e;
		}
	}
	
	/**
	 * 升级母包
	 * @param uuids
	 * @param taskContent
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upgradeTask")
	@ResponseBody
	public Map<String, Object> publishTask(String uuids, String taskContent, String taskType) throws Exception {
		LOGGER.info("uuids :" + uuids + "taskContent :" + taskContent);
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		JSONObject taskContentObject = JSON.parseObject(taskContent);
		
		String[] uuid = uuids.split(",");
		JSONObject result;
		List<SimuatorStatusInfo> simLists = new ArrayList<SimuatorStatusInfo>();
		SimuatorStatusInfo simuatorStatusInfo;
		for (int i = 0; i<uuid.length ;i++) {
		    result=new JSONObject();
		    simuatorStatusInfo = new SimuatorStatusInfo();
			result.put("uuid", uuid[i]);
			simuatorStatusInfo.setUuid(uuid[i]);
			simuatorStatusInfo.setTaskStatus(SimulatorTaskStatusEnum._1.getType());
			simuatorStatusInfo.setTaskType(taskType);
			JSONObject data=new JSONObject();
			data.put("version", taskContentObject.get("toVersion"));
			data.put("url", "http://" + BUCKETNAME + "." + ENDPOINT + "/"+taskContentObject.get("url"));
			data.put("backUrl", "http://qy-crack."+ENDPOINT+"/"+taskContentObject.get("url"));
			data.put("md5", taskContentObject.get("md5"));
			data.put("force", taskContentObject.get("force"));
			data.put("bucketName", BUCKETNAME);
			data.put("fileName", taskContentObject.get("url"));
			result.put("data", data.toJSONString());
			
			LOGGER.warn("result :" + result.toString());
			String queueName=CacheKey.NEW_UPGRADE_QUEUE;
			redisClient.evalLpush(queueName, result.toJSONString());
			simLists.add(simuatorStatusInfo);
		}
		
		simuatorStatusInfoService.updateByUuid(simLists);
		return ResponseMapUtils.responseSuccess();
	}
	
    /**
     * 关闭手机,重启手机，打开手电
     * @param uuids
     * @param taskContent
     * @return
     * @throws Exception
     */
	@RequestMapping(value = "phoneTask")
	@ResponseBody
	public Map<String, Object> phoneTask(String uuids, String actionType, String taskType, String force) throws Exception {
		LOGGER.info("uuids :" + uuids + "actionType :" + actionType);
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		String[] uuid = uuids.split(",");
		JSONObject result;
		List<SimuatorStatusInfo> simLists = new ArrayList<SimuatorStatusInfo>();
		SimuatorStatusInfo simuatorStatusInfo;
		for (int i = 0; i<uuid.length ;i++) {
		    result=new JSONObject();
			result.put("uuid", uuid[i]);
		    simuatorStatusInfo = new SimuatorStatusInfo();
		    simuatorStatusInfo.setUuid(uuid[i]);
		    simuatorStatusInfo.setTaskStatus(SimulatorTaskStatusEnum._1.getType());
			simuatorStatusInfo.setTaskType(taskType);
			
			JSONObject data=new JSONObject();
			data.put("actionType", actionType);
			data.put("force", force);
			data.put("taskId", UUID.randomUUID().toString().replace("-", ""));
			result.put("data", data.toJSONString());
			
			String queueName=CacheKey.NEW_PHONE_QUEUE;
			LOGGER.warn("result :" + result.toString());
			redisClient.evalLpush(queueName, result.toJSONString());
			simLists.add(simuatorStatusInfo);
		}
		simuatorStatusInfoService.updateByUuid(simLists);
		return ResponseMapUtils.responseSuccess();
	}
	
	 /**
	  * 查找机柜
	  * @param clientIp
	  * @return
	  * @throws Exception
	  */
	@RequestMapping(value = "findCabinet")
	@ResponseBody
	public Map<String, Object> findCabinet(String clientIp) throws Exception {
		if(StringUtils.isBlank(clientIp)){
			return ResponseMapUtils.responseFail("clientIp参数不能为空");
		}
		clientIp = clientIp.replaceAll("/", "");
		clientIp = clientIp.substring(0, clientIp.indexOf(".", clientIp.indexOf(".", clientIp.indexOf(".")+1) +1));
		String cabient = simuatorStatusInfoService.getCabientByIp(clientIp);
		if (cabient == null) {
			return ResponseMapUtils.responseSuccess("未找到机柜");	
		}
		return ResponseMapUtils.responseSuccess(cabient);
	}
	
	/**
	 * 清理状态
	 * @param uuids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "clearStatus")
	@ResponseBody
	public Map<String, Object> phoneTask(String uuids) throws Exception {
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		String[] uuid = uuids.split(",");
		List<SimuatorStatusInfo> simLists = new ArrayList<SimuatorStatusInfo>();
		SimuatorStatusInfo simuatorStatusInfo;
		for (int i = 0; i<uuid.length ;i++) {
			simuatorStatusInfo = new SimuatorStatusInfo();
			simuatorStatusInfo.setUuid(uuid[i]);
			simLists.add(simuatorStatusInfo);
		}
		simuatorStatusInfoService.updateStatusByUuid(simLists);
		return ResponseMapUtils.responseSuccess();
	}
	
	/**
	 * 同步状态
	 * @param uuids
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "syncStatus")
	@ResponseBody
	public Map<String, Object> syncStatus() throws Exception {
		simuatorStatusInfoService.syncStatus();
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "clearOffline")
	@ResponseBody
	public Map<String, Object> clearOffline(String uuids) throws Exception {
		simuatorStatusInfoService.clearOffline(uuids);
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "clearOfflineForVer")
	@ResponseBody
	public Map<String, Object> clearOfflineForVer(String bizVer) throws Exception {
		simuatorStatusInfoService.clearOfflineForVer(bizVer);
		return ResponseMapUtils.responseSuccess();
	}
	
	@RequestMapping(value = "checkBusy")
	@ResponseBody
	public Map<String, Object> checkBusy(long busyTime) throws Exception {
		simuatorStatusInfoService.checkBusy(busyTime);
		return ResponseMapUtils.responseSuccess();
	}
	
	/**
	 * 升级心跳包
	 * @param uuids
	 * @param taskContent
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upgradeHeartTask")
	@ResponseBody
	public Map<String, Object> upgradeHeartTask(String uuids, String taskContent, String taskType) throws Exception {
		LOGGER.info("uuids :" + uuids + "taskContent :" + taskContent);
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		JSONObject taskContentObject = JSON.parseObject(taskContent);
		
		String[] uuid = uuids.split(",");
		JSONObject result;
		List<SimuatorStatusInfo> simLists = new ArrayList<SimuatorStatusInfo>();
		SimuatorStatusInfo simuatorStatusInfo;
		for (int i = 0; i<uuid.length ;i++) {
		    result=new JSONObject();
		    simuatorStatusInfo = new SimuatorStatusInfo();
			result.put("uuid", uuid[i]);
			simuatorStatusInfo.setUuid(uuid[i]);
			simuatorStatusInfo.setTaskStatus(SimulatorTaskStatusEnum._1.getType());
			simuatorStatusInfo.setTaskType(taskType);
			JSONObject data=new JSONObject();
			data.put("version", taskContentObject.get("toVersion"));
			data.put("url", "http://qy-crack."+ENDPOINT+"/"+taskContentObject.get("url"));
			data.put("backUrl", "http://qy-crack."+ENDPOINT+"/"+taskContentObject.get("url"));
			data.put("md5", taskContentObject.get("md5"));
			data.put("force", taskContentObject.get("force"));
			data.put("bucketName", BUCKETNAME);
			data.put("fileName", taskContentObject.get("url"));
			result.put("data", data.toJSONString());
			
			LOGGER.warn("result :" + result.toString());
			String queueName=CacheKey.NEW_HEART_UPGRADE_QUEUE;
			redisClient.evalLpush(queueName, result.toJSONString());
			simLists.add(simuatorStatusInfo);
		}
		
		simuatorStatusInfoService.updateByUuid(simLists);
		return ResponseMapUtils.responseSuccess();
	}
	
	/**
	 * 升级系统包
	 * @param uuids
	 * @param taskContent
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upgradeSysApkTask")
	@ResponseBody
	public Map<String, Object> upgradeSysApkTask(String uuids, String taskContent, String taskType) throws Exception {
		LOGGER.info("uuids :" + uuids + "taskContent :" + taskContent);
		if(StringUtils.isBlank(uuids)){
			return ResponseMapUtils.responseFail("uuids参数不能为空");
		}
		
		JSONObject taskContentObject = JSON.parseObject(taskContent);
		String[] uuid = uuids.split(",");
		List<SysApkUpgrade> sysLists = new ArrayList<>();
		SysApkUpgrade sysApk;
		//如果指定了执行个数
		int doCount = 1;
		if (StringUtils.isNotBlank((String)taskContentObject.get("doCount"))) {
			doCount = Integer.valueOf((String)taskContentObject.get("doCount"));
			doCount = uuid.length % doCount == 0 ? uuid.length / doCount : uuid.length / doCount +1;
		}
		String doTime = "";
		if (StringUtils.isNotBlank((String)taskContentObject.get("doTime"))) {
			doTime = (String)taskContentObject.get("doTime");
		}
		int doTranslate = 0;
		if (StringUtils.isNotBlank((String)taskContentObject.get("doTranslate"))) {
			doTranslate = Integer.valueOf((String)taskContentObject.get("doTranslate"));
		}
		for (int i = 0; i<uuid.length ;i++) {
			sysApk = new  SysApkUpgrade();
			sysApk.setUuid(uuid[i]);
			sysApk.setBackUrl((String)taskContentObject.get("url"));
			sysApk.setForce(Integer.valueOf(taskContentObject.get("force").toString()));
			sysApk.setMd5((String)taskContentObject.get("md5"));
			sysApk.setUrl((String)taskContentObject.get("url"));
			sysApk.setModel((String)taskContentObject.get("model"));
			sysApk.setVersion((String)taskContentObject.get("toVersion"));
			//根据余数设定触发时间
			
			int remainder = i % doCount;
			Calendar nowTime = Calendar.getInstance();
			Date nowDate = nowTime.getTime();
			if (StringUtils.isNotBlank(doTime)) {
				if (doTranslate == 0) {
					Date newDate = new Date(DateUtil.stringToDate((String)taskContentObject.get("doTime"), DateUtil.DATE_PATTEN_YY_MM_DD_HHMMSS).getTime() + remainder * 300000);
					sysApk.setDoTime(newDate);	
				} else {
					Date newDate = new Date(DateUtil.stringToDate((String)taskContentObject.get("doTime"), DateUtil.DATE_PATTEN_YY_MM_DD_HHMMSS).getTime() + remainder * doTranslate * 60 * 1000);
					sysApk.setDoTime(newDate);	
				}
			} else {
				if (doTranslate == 0) {
					Date newDate = new Date(nowDate.getTime() + remainder * 300000);
					sysApk.setDoTime(newDate);	
				} else {
					Date newDate = new Date(nowDate.getTime() + remainder * doTranslate * 60 * 1000);
					sysApk.setDoTime(newDate);	
				}
				
			}
			
			sysLists.add(sysApk);
		}
		
		sysApkUpgradeService.batchInsert(sysLists);
		return ResponseMapUtils.responseSuccess();
	}
	
	/**
	 * 升级系统包
	 * @param uuids
	 * @param taskContent
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upgradeSysApkTaskByType")
	@ResponseBody
	public Map<String, Object> upgradeSysApkTaskByType(String taskContent) throws Exception {
		LOGGER.info("taskContent :" + taskContent);
		
		JSONObject taskContentObject = JSON.parseObject(taskContent);
		String model = (String)taskContentObject.get("model");
		List<SimuatorStatusInfo> simLists = simuatorStatusInfoService.selectByModel(model);
		if (CollectionUtils.isEmpty(simLists)) {
			return null;
		}		
		List<SysApkUpgrade> sysLists = new ArrayList<>();
		SysApkUpgrade sysApk;
		//如果指定了执行个数
		int doCount = 1;
		if (StringUtils.isNotBlank((String)taskContentObject.get("doCount"))) {
			doCount = Integer.valueOf((String)taskContentObject.get("doCount"));
			doCount = simLists.size() % doCount == 0 ? simLists.size() / doCount : simLists.size() / doCount +1;
		}
		String doTime = "";
		if (StringUtils.isNotBlank((String)taskContentObject.get("doTime"))) {
			doTime = (String)taskContentObject.get("doTime");
		}
		int doTranslate = 0;
		if (StringUtils.isNotBlank((String)taskContentObject.get("doTranslate"))) {
			doTranslate = Integer.valueOf((String)taskContentObject.get("doTranslate"));
		}
		for (int i = 0; i<simLists.size() ;i++) {
			sysApk = new  SysApkUpgrade();
			sysApk.setUuid(simLists.get(i).getUuid());
			sysApk.setBackUrl((String)taskContentObject.get("url"));
			sysApk.setForce(Integer.valueOf(taskContentObject.get("force").toString()));
			sysApk.setMd5((String)taskContentObject.get("md5"));
			sysApk.setUrl((String)taskContentObject.get("url"));
			sysApk.setModel((String)taskContentObject.get("model"));
			sysApk.setVersion((String)taskContentObject.get("toVersion"));
			//根据余数设定触发时间
			
			int remainder = i % doCount;
			Calendar nowTime = Calendar.getInstance();
			Date nowDate = nowTime.getTime();
			if (StringUtils.isNotBlank(doTime)) {
				if (doTranslate == 0) {
					Date newDate = new Date(DateUtil.stringToDate((String)taskContentObject.get("doTime"), DateUtil.DATE_PATTEN_YY_MM_DD_HHMMSS).getTime() + remainder * 300000);
					sysApk.setDoTime(newDate);	
				} else {
					Date newDate = new Date(DateUtil.stringToDate((String)taskContentObject.get("doTime"), DateUtil.DATE_PATTEN_YY_MM_DD_HHMMSS).getTime() + remainder * doTranslate * 60 * 1000);
					sysApk.setDoTime(newDate);	
				}
			} else {
				if (doTranslate == 0) {
					Date newDate = new Date(nowDate.getTime() + remainder * 300000);
					sysApk.setDoTime(newDate);	
				} else {
					Date newDate = new Date(nowDate.getTime() + remainder * doTranslate * 60 * 1000);
					sysApk.setDoTime(newDate);	
				}
				
			}
			
			sysLists.add(sysApk);
		}
		
		sysApkUpgradeService.batchInsert(sysLists);
		return ResponseMapUtils.responseSuccess();
	}
	
	/**
	 * 待执行任务查询
	 * 
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "seachSysTask")
	public String seachSysTask(Model model) throws Exception {
		return "/simuatorStatusInfo/searchSysTask";
	}
	
	/**
	 * 待执行系统报任务列表数据
	 * @param page
	 * @param simuatorStatusInfo
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "sysInfoPage")
	@ResponseBody
	public Map<String, Object> sysInfoPage(DataGridModel page, SysApkUpgrade sysApkUpgrade) throws Exception {
		try{
			sysApkUpgrade = (sysApkUpgrade == null ? new SysApkUpgrade() : sysApkUpgrade);
			sysApkUpgrade.setPageInfo(page);
			
			Map<String, Object> results = new HashMap<String, Object>();
			results.put("total", sysApkUpgradeService.findPageCount(sysApkUpgrade));
			
			List<SysApkUpgrade> sysApkList = sysApkUpgradeService.findPageList(sysApkUpgrade);
			results.put("rows", sysApkList);
			return results;
		}catch(Exception e){
			LOGGER.error("",e);
			throw e;
		}
	}
}

